<?php

namespace App\Exceptions;

use App\Exceptions\my\MyException;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        InterfaceLog($exception->getMessage(), $request->path(), 2);
//        无效的token
        if ($exception instanceof TokenInvalidException) {
            return response()->json(['code'=>400, 'msg'=>'请不要随易捏造token']);
        }
        //        无效的token
        if ($exception instanceof TokenExpiredException) {
            return response()->json(['code'=>401, 'msg'=>'登录失效']);
        }
        //        自定义异常
        if ($exception instanceof MyException) {
            return response()->json(['code'=>402, 'msg'=>$exception->getMessage()]);
        }
        if ($exception instanceof UnauthorizedHttpException) {
            if ($exception->getPrevious() instanceof TokenExpiredException) {
                return response()->json(['code'=>401, 'msg'=>'登录失效']);
            } else if ($exception->getPrevious() instanceof TokenInvalidException) {
                return response()->json(['code'=>400, 'msg'=>'请不要随易捏造token']);
            } else if ($exception->getPrevious() instanceof TokenBlacklistedException) {
                return response()->json(['code' => 402, 'msg' => 'token异常']);
            } else {
                return response()->json(['code'=>400, 'msg'=>$exception->getMessage()??'token缺失']);
            }
        }
       return response()->json(['code'=>500, 'msg'=>$exception->getMessage()??'服务器繁忙，请稍后再试']);
        // return parent::render($request, $exception); //todo 线上则注释该行，本地调试时打开
    }
}
